package com.sdkx.wear_os.utils

import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.util.Base64
import androidx.annotation.DrawableRes
import com.sdkx.wear_os.app.MyApplication
import com.sdkx.wear_os.utils.ToastLogUtils.logUtil
import com.sdkx.wear_os.utils.ToastLogUtils.toastUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.*
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL
import java.util.regex.Matcher
import java.util.regex.Pattern


/**
 * 检查是否有SD卡
 */
fun checkSDCardAvailable(): Boolean {
    return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
}

/**
 * 存储路径
 */
fun savePath(): File {
    return if (checkSDCardAvailable()) {
        File(MyApplication.application.getExternalFilesDir(null)?.absolutePath, "")
    } else {
        File(Environment.getDataDirectory(), "")
    }
}

/**
 * 文件存储
 */
fun saveFile(content: String?, fileName: String) {
    val appDir: File = savePath()
    if (!appDir.exists()) {
        appDir.mkdir()
    }
    val file = File(appDir, fileName)
    try {
        val fos = FileOutputStream(file, true)
        val osw = OutputStreamWriter(fos)
        osw.write(content)
        osw.flush()
        osw.close()
        fos.flush()
        fos.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }
}

/**
 * 保存图片到图库
 */
fun savePicture(context: Context, file: File) {
    try {
        val values = ContentValues()
        values.put(MediaStore.Images.Media.DATA, file.absolutePath)
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
        context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
    } catch (e: FileNotFoundException) {
        e.printStackTrace()
    }
    // 最后通知图库更新
    val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
    val contentUri = Uri.fromFile(file)
    mediaScanIntent.data = contentUri
    context.sendBroadcast(mediaScanIntent)
    toastUtil("保存成功")
}

/**
 * 协程保存图片到图库
 */
suspend fun savePicture(context: Context, bitmap: Bitmap) {
    withContext(Dispatchers.IO) {
        val saveUri = context.contentResolver.insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            ContentValues()
        ) ?: kotlin.run {
            MainScope().launch { toastUtil("存储失败") }
            return@withContext
        }
        context.contentResolver.openOutputStream(saveUri).use {
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, it)) {
                MainScope().launch {
                    toastUtil("存储成功")
                }
            } else {
                MainScope().launch {
                    toastUtil("存储失败")
                }
            }
        }
    }
}

/**
 * 保存图片到图库
 */
fun saveBitmap(context: Context, bitmap: Bitmap) {
    // 首先保存图片
    val appDir = savePath()
    if (!appDir.exists()) {
        appDir.mkdir()
    }
    val fileName = System.currentTimeMillis().toString() + ".jpg"
    val file = File(appDir, fileName)
    try {
        val fos = FileOutputStream(file)
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
        fos.flush()
        fos.close()
    } catch (e: FileNotFoundException) {
        e.printStackTrace()
    } catch (e: IOException) {
        e.printStackTrace()
    }

    try {
        // 其次把文件插入到系统图库
        val values = ContentValues()
        values.put(MediaStore.Images.Media.DATA, file.absolutePath)
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
        context.contentResolver
            .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
    } catch (e: FileNotFoundException) {
        e.printStackTrace()
    }
    // 最后通知图库更新
    context.sendBroadcast(
        Intent(
            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
            Uri.parse(file.absolutePath)
        )
    )
    toastUtil("下载成功")
}

/**
 * 删除已存储的文件
 */
fun deleteFile(fileName: String) {
    try {
        // 找到文件所在的路径并删除该文件
        val appDir = savePath()
        if (appDir.exists()) {
            val file = File(appDir, fileName)
            file.delete()
        }
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
    }
}

/**
 * 读取文本内容
 */
fun readTxtFile(strFilePath: String): String {
    var content = "" //文件内容字符串
    //打开文件
    val file = File(strFilePath)
    //如果path是传递过来的参数，可以做一个非目录的判断
    if (file.isDirectory) {
        logUtil("TestFile", "The File doesn't not exist.")
    } else {
        try {
            val instream: InputStream = FileInputStream(file)
            val inputreader = InputStreamReader(instream)
            val buffreader = BufferedReader(inputreader)
            var line: String
            //分行读取
            while (buffreader.readLine().also { line = it } != null) {
                content += """
                    $line
                    
                    """.trimIndent()
            }
            instream.close()
        } catch (e: FileNotFoundException) {
            logUtil("TestFile", "The File doesn't not exist.")
        } catch (e: IOException) {
            logUtil("TestFile", e.message)
        } catch (e: NullPointerException) {
            logUtil("TestFile", e.message)
        }
    }
    return content
}

/**
 * 读取raw文件内容
 */
//fun readTxtFile(): String {
//    val sb = StringBuffer()
//    var `is`: InputStream? = null
//    var isr: InputStreamReader? = null
//    var br: BufferedReader? = null
//    var str: String? = ""
//    val resources: Resources = MyApplication.application.resources
//    try {
//        `is` = resources.openRawResource(R.raw.agreement) // 读取相应的章节
//        isr = InputStreamReader(`is`, "UTF-8") // 这里添加了UTF-8，解决乱码问题
//        br = BufferedReader(isr)
//        while (br.readLine().also { str = it } != null) {
//            sb.append(str)
//            sb.append('\n')
//        }
//        br.close()
//        isr.close()
//        `is`.close()
//    } catch (e: FileNotFoundException) {
//        e.printStackTrace()
//    } catch (e: UnsupportedEncodingException) {
//        e.printStackTrace()
//    } catch (e: IOException) {
//        e.printStackTrace()
//    }
//    return sb.toString()
//}

fun getResourcesUri(@DrawableRes id: Int): String {
    val resources: Resources = MyApplication.application.resources
    return ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
            resources.getResourcePackageName(id) + "/" +
            resources.getResourceTypeName(id) + "/" +
            resources.getResourceEntryName(id)
}

/**
 * <读取Json文件的工具类>
 *
 * @author: 小嵩
 * @date: 2017/3/16 16:22
</读取Json文件的工具类> */
class GetJsonDataUtil {
    fun getJson(context: Context, fileName: String?): String {
        val stringBuilder = StringBuilder()
        try {
            val assetManager = context.assets
            val bf = BufferedReader(
                InputStreamReader(
                    assetManager.open(fileName!!)
                )
            )
            var line: String?
            while (bf.readLine().also { line = it } != null) {
                stringBuilder.append(line)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return stringBuilder.toString()
    }
}

/**
 * 获取图片字符串中所有链接
 * @param htmlStr html字符串
 * @return
 */
fun getImgStr(htmlStr: String?): MutableList<String> {
    val pics: MutableList<String> = mutableListOf()
    var img = ""
    val p_image: Pattern
    val m_image: Matcher
    //图片链接地址
    val regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>"
    p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE)
    m_image = p_image.matcher(htmlStr)
    while (m_image.find()) {
        // 得到<img />数据
        img = m_image.group()
        // 匹配<img>中的src数据
        val m: Matcher =
            Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img)
        while (m.find()) {
            pics.add(m.group(1))
        }
    }
    return pics
}

/**
 * uri转string
 */
fun getPath(context: Context, uri: Uri): String? {
    if ("content".equals(uri.scheme, ignoreCase = true)) {
        val projection = arrayOf("_data")
        var cursor: Cursor? = null
        try {
            cursor = context.contentResolver.query(uri, projection, null, null, null)
            val column_index = cursor!!.getColumnIndexOrThrow("_data")
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index)
            }
        } catch (e: Exception) {
        }
    } else if ("file".equals(uri.scheme, ignoreCase = true)) {
        return uri.path
    }
    return null
}

/**
 * bitmap转file
 */
fun getFile(bitmap: Bitmap): File {
    val baos = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos)
    val file =
        File(MyApplication.application.getExternalFilesDir(null)?.absolutePath + "/temp.jpg")
    try {
        file.createNewFile()
        val fos = FileOutputStream(file)
        val `is`: InputStream = ByteArrayInputStream(baos.toByteArray())
        var x = 0
        val b = ByteArray(1024 * 100)
        while (`is`.read(b).also { x = it } != -1) {
            fos.write(b, 0, x)
        }
        fos.close()
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
    }
    return file
}

/**
 * bitmap转为base64
 *
 * @param bitmap
 * @return
 */
fun bitmapToBase64(bitmap: Bitmap?): String {
    var result: String = ""
    var baos: ByteArrayOutputStream? = null
    try {
        if (bitmap != null) {
            baos = ByteArrayOutputStream()
            bitmap.compress(Bitmap.CompressFormat.JPEG, 10, baos)
            baos.flush()
            baos.close()
            val bitmapBytes = baos.toByteArray()
            result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT)
        }
    } catch (e: IOException) {
        e.printStackTrace()
    } finally {
        try {
            if (baos != null) {
                baos.flush()
                baos.close()
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
    return result
}

/**
 * base64转为bitmap
 * @param base64Data1
 * @return
 */
fun base64ToBitmap(base64Data1: String): Bitmap? {
    var base64Data = base64Data1
    return try {
        if (base64Data.startsWith("data:image")) {
            base64Data = base64Data.substring(base64Data.indexOf(","))
        }
        val bytes = Base64.decode(base64Data, Base64.DEFAULT)
        BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
    } catch (e: java.lang.Exception) {
        null
    }
}

/**
 * 网络url转bitmap
 *
 * @return
 */
fun urlToBitMap(url: String?): Bitmap? {
    var bitmap: Bitmap? = null
    val thread = Thread {
        var imageurl: URL? = null
        try {
            imageurl = URL(url)
        } catch (e: MalformedURLException) {
            e.printStackTrace()
        }
        try {
            val conn = imageurl!!.openConnection() as HttpURLConnection
            conn.doInput = true
            conn.connect()
            val `is` = conn.inputStream
            bitmap = BitmapFactory.decodeStream(`is`)
            `is`.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
    thread.start()
    try {
        //阻塞 直到线程走完
        thread.join()
    } catch (e: InterruptedException) {
        e.printStackTrace()
    }
    return bitmap
}
